package com.ikun.kunpicturebackend.manager.upload;

import cn.hutool.core.io.FileUtil;
import com.ikun.kunpicturebackend.config.CosClientConfig;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.PicOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 通用的对象存储操作类
 */
@Component
public class CosManager {

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private COSClient cosClient;


    /**
     * 上传对象
     * @param key 对象键(Key)是对象在存储桶中的唯一标识。/上传路径
     * @param file 文件
     * @return
     */
    public PutObjectResult putObject(String key, File file) {
        // 获取桶名
        String bucket = cosClientConfig.getBucket();
        // 构造上传请求
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, key, file);

        // 图片压缩转为webp格式
        String webpKey = FileUtil.mainName(key) + ".webp";
        // 图片处理规则
        List<PicOperations.Rule> ruleList = new ArrayList<>();
        PicOperations.Rule rule = new PicOperations.Rule();
        // 设置规则
        rule.setBucket(bucket);
        // fileid: 处理后文件的保存路径及名称
        // 当fileid与ObjectKey相同时，处理后的文件将覆盖原文件存储；不相同时将分别存储原文件和处理后文件
        rule.setFileId(webpKey);
        rule.setRule("imageMogr2/format/webp");
        ruleList.add(rule);

        // 大小大于20KB才缩略
        if (FileUtil.size(file) > 20 * 1024) {
            // 缩略图处理
            PicOperations.Rule thumbnailRule = new PicOperations.Rule();
            thumbnailRule.setBucket(bucket);
            String thumbnailKey = FileUtil.mainName(key) + "_thumbnail." + FileUtil.getSuffix(key);
            thumbnailRule.setFileId(thumbnailKey);
            // 设置缩略图规则 /thumbnail/<Width>x<Height>:限定缩略图的宽度和高度的最大值分别为 Width 和 Height，进行等比缩放
            // 如果大于原图宽高则不处理
            thumbnailRule.setRule(String.format("imageMogr2/thumbnail/%sx%s", 128, 128));
            ruleList.add(thumbnailRule);
        }

        // 对图片进行处理（获取基本信息也被视作为一种处理）
        PicOperations picOperations = new PicOperations();
        // 1表示返回原图信息
        picOperations.setIsPicInfo(1);
        picOperations.setRules(ruleList);
        putObjectRequest.setPicOperations(picOperations);
        // 执行
        return cosClient.putObject(putObjectRequest);
    }

    /**
     * 下载对象
     * @param key 对象键(Key)是对象在存储桶中的唯一标识。
     * @return
     */
    public COSObject getObject(String key) {
        GetObjectRequest getObjectRequest = new GetObjectRequest(cosClientConfig.getBucket(), key);
        return cosClient.getObject(getObjectRequest);
    }

    /**
     * 删除对象
     * @param key
     */
    public void deleteObject(String key) {
        cosClient.deleteObject(cosClientConfig.getBucket(), key);
    }
}
